package com.yoomiito.app.ui.cicle;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scrat.app.selectorlibrary.ImageSelector;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.cicle.CiclePublishImageAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.cicle.CicleProductnfo;
import com.yoomiito.app.model.cicle.ImageBean;
import com.yoomiito.app.ui.order.list.OrderActivity;
import com.yoomiito.app.permission.MPermission;
import com.yoomiito.app.present.cicle.CiclePublishPresenter;
import com.yoomiito.app.widget.ItemView;
import com.yoomiito.app.widget.MyItemDecoration;
import com.yoomiito.app.widget.dialog.TipDialog;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.router.Router;

public class CiclePublishActivity extends BaseActivity<CiclePublishPresenter> {
    private final static int MAX_IMAGE_NUM = 9;
    @BindView(R.id.et_content)
    public EditText mContentEt;
    public List<ImageBean> imageBeanList = new ArrayList<>();
    public int publishType = Constant.PUBLISH_TYPE_GOODS;
    @BindView(R.id.iv_buy_goods)
    ItemView mBuyGoodsIv;
//    @BindView(R.id.rg_type)
//    RadioGroup mTypeRg;
//    @BindView(R.id.rb_good)
//    RadioButton mGoodRb;
    @BindView(R.id.btn_publish)
    Button mPublishBtn;
    @BindView(R.id.rv_photo)
    RecyclerView mPhotoRv;
    private CiclePublishImageAdapter mPublishImageAdapter;
    private static int REQUEST_SELECT_IMAGES_CODE = 7;
    private static int REQUEST_PHOTO_CODE = 8;
    public static int CODE_PUBLISH_CICLE = 100;
    private ArrayList<String> mImagePathList = new ArrayList<>();
    private PopupWindow popupWindow;
    private static final int MAX_PHOTO_SIZE = 9;
    private TipDialog tipDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_cicle_publish;
    }

    @Override
    public CiclePublishPresenter newP() {
        return new CiclePublishPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        imageBeanList.add(new ImageBean(null, true, true));
        mPublishImageAdapter = new CiclePublishImageAdapter(imageBeanList);
        initView();
        requestBasicPermission();
        publishType = Constant.PUBLISH_TYPE_GOODS;
        mBuyGoodsIv.setVisibility(View.VISIBLE);
//        mGoodRb.setChecked(true);
//        mTypeRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
//                switch (checkedId) {
//                    case R.id.rb_good:
//                        publishType = Constant.PUBLISH_TYPE_GOODS;
//                        mBuyGoodsIv.setVisibility(View.VISIBLE);
//                        break;
//                    case R.id.rb_life:
//                        publishType = Constant.PUBLISH_TYPE_LIFE;
//                        mBuyGoodsIv.setVisibility(View.GONE);
//                        break;
//                }
//                resetData();
//            }
//        });

    }

    private void initView() {
        checkBtnState();
        mPhotoRv.addItemDecoration(new MyItemDecoration(context, RecyclerView.VERTICAL));
        mPhotoRv.setLayoutManager(new GridLayoutManager(this, 3));

        mPhotoRv.setAdapter(mPublishImageAdapter);
        mPublishImageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (imageBeanList.get(position).isAdd()) {
                    showPopueWindow();
                } else {
                }
            }
        });
        mPublishImageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                YMToast.showText("fffffffffff");
            }
        });
        mPublishImageAdapter.setOnRemoveListener(new CiclePublishImageAdapter.OnRemoveListener() {
            @Override
            public void onRemove(View v, ImageBean bean) {
                imageBeanList.remove(bean);
                if (imageBeanList.size() == 8) {
                    imageBeanList.add(new ImageBean("", true, true));//然后再添加“添加图片”
                }
                mPublishImageAdapter.setNewData(imageBeanList);
                checkBtnState();
            }
        });

        mContentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                checkBtnState();
            }
        });

        mContentEt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 解决scrollView中嵌套EditText导致不能上下滑动的问题
                v.getParent().requestDisallowInterceptTouchEvent(true);
                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_UP:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });
    }

    @OnClick({R.id.iv_buy_goods, R.id.btn_publish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_buy_goods:
                Router.newIntent(this)
                        .to(OrderActivity.class)
                        .requestCode(Constant.CODE_GET_ORDER_INFO_REQUEST_ID)
                        .putInt(Constant.TYPE, Constant.CODE_GET_ORDER_INFO_REQUEST_ID)
                        .launch();
                break;
            case R.id.btn_publish:
                showLoading();
                getP().uploadPhotos(0);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            List<String> imagePaths = ImageSelector.getImagePaths(data);
            mImagePathList.addAll(imagePaths);
            addImages(imagePaths, true);
            checkBtnState();
        } else if (requestCode == Constant.CODE_GET_ORDER_INFO_REQUEST_ID && resultCode == Constant.CODE_GET_ORDER_INFO_RESULT_ID) {
            getP().setProductId(data.getStringExtra(Constant.KEY_PRODUCT_ID));
            getP().setOrderId(data.getStringExtra(Constant.KEY_ORDER_ID));
            getP().setGoodsType(data.getIntExtra(Constant.KEY_ORDER_TYPE, 0));
            String title = data.getStringExtra(Constant.KEY_TITLE);
            mBuyGoodsIv.setRightText(title);
            getP().getProductInfoData();
            checkBtnState();
        }else if (requestCode == REQUEST_PHOTO_CODE) {
            if (resultCode==RESULT_OK){
                List<String> imagePaths = new ArrayList<>();
                imagePaths.add(getP().getmCurrentPhotoPath());
                mImagePathList.addAll(imagePaths);
                addImages(imagePaths, true);
                checkBtnState();
            }
        }
    }

    private Bitmap compressPixel(String filePath) {
        Bitmap bmp = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        //setting inSampleSize value allows to load a scaled down version of the original image
        options.inSampleSize = 2;

        //inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[16 * 512];
        try {
            //load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
            if (bmp == null) {

                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(filePath);
                    BitmapFactory.decodeStream(inputStream, null, options);
                    inputStream.close();
                } catch (FileNotFoundException exception) {
                    exception.printStackTrace();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        } finally {
            return bmp;
        }
    }

    private void setImage() {
        mPublishImageAdapter.setNewData(imageBeanList);
    }

    private void addImages(List<String> imagePaths, boolean isLocalImage) {
        if (imageBeanList.size() > 0) {
            imageBeanList.remove(imageBeanList.size() - 1);//首先移除添加图片
        }
        for (String path : imagePaths) {//把选择回来的图片加入list
            if (isLocalImage) {
                imageBeanList.add(new ImageBean(path, false, true));
            } else {
                imageBeanList.add(new ImageBean(path, false, false));
            }
            if (imageBeanList.size() >= MAX_IMAGE_NUM) {
                break;
            }
        }
        if (imageBeanList.size() < MAX_IMAGE_NUM) {
            imageBeanList.add(new ImageBean("", true, true));//然后再添加“添加图片”
        }
        setImage();
    }

    public void setmBuyGoodsData(CicleProductnfo data) {
        mContentEt.setText(data.getTitle());
        imageBeanList.clear();
        addImages(data.getImgurl(), false);
        checkBtnState();
    }

    private void showPopueWindow() {
        View popView = View.inflate(this, R.layout.popupwindow_camera_need, null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels * 1 / 3;

        final PopupWindow popupWindow = new PopupWindow(popView, weight, height);
//        popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(i, REQUEST_SELECT_IMAGES_CODE);
                //相册
                int remainSize = MAX_PHOTO_SIZE -imageBeanList.size() + 1;
                ImageSelector.show(context, REQUEST_SELECT_IMAGES_CODE, remainSize);
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getP().takeCamera(REQUEST_PHOTO_CODE);
                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);
    }

    private void checkBtnState() {
        if (imageBeanList.size() > 1 && mContentEt != null && !TextUtils.isEmpty(mContentEt.getText())) {
            if (publishType == Constant.PUBLISH_TYPE_LIFE) {
                mPublishBtn.setEnabled(true);
            } else if (!TextUtils.isEmpty(getP().getProductId())
                    && !TextUtils.isEmpty(getP().getOrderId())
                    && getP().getGoodsType() != -1) {
                mPublishBtn.setEnabled(true);
            } else {
                mPublishBtn.setEnabled(false);
            }
        } else {
            mPublishBtn.setEnabled(false);
        }

    }

    /**
     * 申请相机权限
     */
    private void requestBasicPermission() {
        MPermission.with(this)
                .setRequestCode(0)
                .permissions(
                        Manifest.permission.CAMERA
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void resetData(){
        mBuyGoodsIv.setRightText(getString(R.string.cicle_select));
        mContentEt.setText("");
        mImagePathList = new ArrayList<>();
        imageBeanList.clear();
        imageBeanList.add(new ImageBean("", true, true));//然后再添加“添加图片”
        mPublishImageAdapter.setNewData(imageBeanList);
        getP().setGoodsType(-1);
        getP().setOrderId("");
        getP().setProductId("");
        checkBtnState();
    }

    public void showTip(String data){
        if (tipDialog==null){
            tipDialog = new TipDialog(this);
        }
        tipDialog.setContent(data);
        tipDialog.show();
    }

}
